import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    cityExist: false,
    cityName: '',
    cityData: [],
    isTabbarShow: true,
    topNews: [],
    isLogin: false,
    username: ''
  },
  mutations: {
    cityExistMutation(state, data) {
      state.cityExist = data;
    },
    cityNameMutation(state, data) {
      state.cityName = data;
    },
    cityDataMutation(state, data) {
      if (data.future) {
        data.future.pop();
      }
      state.cityData = data;
    },
    showTabbar(state, data) {
      state.isTabbarShow = data;
    },
    topNewsMutation(state, data) {
      state.topNews = data;
    },
    loginMutation(state, data) {
      state.isLogin = data.isLogin;
      state.username = data.username;
    }
  },
  actions: {
    async queryCity({ commit, state }) {
      try {
        const res = await axios.get(`/simpleWeather/query?city=${state.cityName}&key=738f37aa8cb7b0cc8df46d795695a716`);
        commit('cityExistMutation', !res.data.error_code);
      } catch (error) {
        console.error('Failed to query city:', error);
        commit('cityExistMutation', false);
      }
    },
    async getCityData({ commit, state }) {
      try {
        const res = await axios.get(`/simpleWeather/query?city=${state.cityName}&key=738f37aa8cb7b0cc8df46d795695a716`);
        if (res.data.result) {
          commit('cityDataMutation', res.data.result);
        } else {
          console.error('Failed to get city data:', res.data.reason);
          commit('cityDataMutation', []);
        }
      } catch (error) {
        console.error('Failed to get city data:', error);
        commit('cityDataMutation', []);
      }
    },
    async getTopNews({ commit }) {
      try {
        const res = await axios.get('/toutiao/index?type=top&key=7c502deb63c7135c7270f2b43ecb93da');
        if (res.data.result && res.data.result.data) {
          commit('topNewsMutation', res.data.result.data);
        } else {
          console.error('Failed to get top news:', res.data.reason);
          commit('topNewsMutation', []);
        }
      } catch (error) {
        console.error('Failed to get top news:', error);
        commit('topNewsMutation', []);
      }
    }
  }
});
